package com.budwk.app.sqfw.services.datamange.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.CommonForAdminConstants;
import com.budwk.app.sqfw.constants.DataManageConstants;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.datamange.*;
import com.budwk.app.sqfw.vo.SqfwDataMangeCheckVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

import java.util.List;

@Slf4j
@IocBean
public class DataMangeCheckServiceImpl implements DataMangeCheckService {
    @Inject
    private SysUserService sysUserService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private DataMangeStreetCheckService dataMangeStreetCheckService;
    @Inject
    private DataMangeDistrictCheckService dataMangeDistrictCheckService;
    @Inject
    private DataMangeCityCheckService dataMangeCityCheckService;
    @Inject
    private DataMangeProvinceCheckService dataMangeProvinceCheckService;
    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Override
    public Pagination page(SqfwDataMangeCheckVO bean) {
        if (null == bean) {
            bean = new SqfwDataMangeCheckVO();
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("DataMangeCheckServiceImpl-list-SQL: {}", criteria.toString());

        String areaLevel = checkUserArea();
        if (StringUtils.isEmpty(areaLevel)) {
            throw new AppException("用户行政区域参数错误!");
        }
        Pagination pagination = new Pagination();
        switch (areaLevel) {
            case CommonForAdminConstants.PROVINCE:
                pagination = dataMangeProvinceCheckService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
                break;
            case CommonForAdminConstants.CITY:
                pagination = dataMangeCityCheckService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
                break;
            case CommonForAdminConstants.DISTRICT:
                pagination = dataMangeDistrictCheckService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
                break;
            case CommonForAdminConstants.COUNTY:
                pagination = dataMangeStreetCheckService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
                break;
        }
        log.info("DataMangeCheckServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    /**
     * 审核接口
     * 这里总的有三个操作：
     * 1. 在审核表sqfw_datamange_community_check中插入一条记录,插入之前先查询该部门下是否有记录，如果有则进行逻辑删除，再进行新审核记录插入
     * 2. 审核完成后，将审核数据插入上一级的主表sqfw_datamange
     * 3. 更新原表sqfw_form_summary_new记录audit_status状态为“已上报“
     *
     * @param bean
     */
    @Override
    public SqfwDataMangeCheckVO check(SqfwDataMangeCheckVO bean) {
        String areaLevel = checkUserArea();
        //String areaLevel = CommonForAdminConstants.COUNTY;
        if (StringUtils.isEmpty(areaLevel)) {
            throw new AppException("用户行政区域参数错误!");
        }
        SqfwDataMangeCheckVO sqfwDataMangeCheckVO = new SqfwDataMangeCheckVO();
        switch (areaLevel) {
            case CommonForAdminConstants.PROVINCE:
                sqfwDataMangeCheckVO = dataMangeProvinceCheckService.check(bean);
                break;
            case CommonForAdminConstants.CITY:
                sqfwDataMangeCheckVO = dataMangeCityCheckService.check(bean);
                break;
            case CommonForAdminConstants.DISTRICT:
                sqfwDataMangeCheckVO = dataMangeDistrictCheckService.check(bean);
                break;
            case CommonForAdminConstants.COUNTY:
                sqfwDataMangeCheckVO = dataMangeStreetCheckService.check(bean);
                break;
        }
        return sqfwDataMangeCheckVO;
    }

    /**
     * 上报审核后的数据
     * 这里总的有三个操作：
     * 1. 在审核表sqfw_datamange_community_check中插入一条记录,插入之前先查询该部门下是否有记录，如果有则进行逻辑删除，再进行新审核记录插入
     * 2. 审核完成后，将审核数据插入上一级的主表sqfw_datamange
     * 3. 更新原表sqfw_form_summary_new记录audit_status状态为“已上报“
     *
     * @param bean
     */
    @Override
    public void report(SqfwDataMangeCheckVO bean) {
        String areaLevel = checkUserArea();
        if (StringUtils.isEmpty(areaLevel)) {
            throw new AppException("用户行政区域参数错误!");
        }
        switch (areaLevel) {
            case CommonForAdminConstants.PROVINCE:
                dataMangeProvinceCheckService.report(bean);
                break;
            case CommonForAdminConstants.CITY:
                dataMangeCityCheckService.report(bean);
                break;
            case CommonForAdminConstants.DISTRICT:
                dataMangeDistrictCheckService.report(bean);
                break;
            case CommonForAdminConstants.COUNTY:
                dataMangeStreetCheckService.report(bean);
                break;
        }
    }

    /**
     * 查询有数据的日期
     */
    public List<String> queryDataTime(String type, String subType) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        if (StringUtils.isNotEmpty(type)) {
            criSql.andEquals("type", type);
        }
        if (StringUtils.isNotEmpty(subType)) {
            criSql.andEquals("sub_type", subType);
        }
        String tableName = getTableNameByArea();
        Dao dao = NutzIocUtils.getBean(Dao.class);
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT DISTINCT substring(create_date::text, 1,10) FROM shequ.\"").append(tableName).append("\"").append(cri.toString());
        Sql sql = Sqls.create(sb.toString());
        sql.setCallback(Sqls.callback.strList());
        dao.execute(sql);
        return sql.getList(String.class);
    }

    /**
     * 详情查询
     */
    @Override
    public SqfwDataMangeCheckVO queryDetail(SqfwDataMangeCheckVO bean) {
        if (null == bean) {
            bean = new SqfwDataMangeCheckVO();
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("DataMangeCheckServiceImpl-queryDetail-SQL: {}", criteria.toString());

        String areaLevel = checkUserArea();
        if (StringUtils.isEmpty(areaLevel)) {
            throw new AppException("用户行政区域参数错误!");
        }
        SqfwDataMangeCheckVO sqfwDataMangeCheckVO = new SqfwDataMangeCheckVO();
        switch (areaLevel) {
            case CommonForAdminConstants.PROVINCE:
                Sqfw_datamange_province_check sqfwDatamangeProvinceCheck = dataMangeProvinceCheckService.fetch(bean.getId());
                BeanUtil.copyProperties(sqfwDatamangeProvinceCheck, sqfwDataMangeCheckVO);
                break;
            case CommonForAdminConstants.CITY:
                Sqfw_datamange_city_check sqfwDatamangeCityCheck = dataMangeCityCheckService.fetch(bean.getId());
                BeanUtil.copyProperties(sqfwDatamangeCityCheck, sqfwDataMangeCheckVO);
                break;
            case CommonForAdminConstants.DISTRICT:
                Sqfw_datamange_district_check sqfwDatamangeDistrictCheck = dataMangeDistrictCheckService.fetch(bean.getId());
                BeanUtil.copyProperties(sqfwDatamangeDistrictCheck, sqfwDataMangeCheckVO);
                break;
            case CommonForAdminConstants.COUNTY:
                Sqfw_datamange_street_check sqfwDatamangeStreetCheck = dataMangeStreetCheckService.fetch(bean.getId());
                BeanUtil.copyProperties(sqfwDatamangeStreetCheck, sqfwDataMangeCheckVO);
                break;
        }
        log.info("DataMangeCheckServiceImpl-queryDetail-耗时: {}ms", System.currentTimeMillis() - startTime);
        return sqfwDataMangeCheckVO;
    }

    /**
     * 检查当前登录用户的行政区域级别
     *
     * @return
     */
    private String checkUserArea() {
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (StringUtils.isEmpty(sysUser.getProvince()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getProvince())) {
            return CommonForAdminConstants.PROVINCE;
        } else if (StringUtils.isEmpty(sysUser.getCity()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getCity())) {
            return CommonForAdminConstants.PROVINCE;
        } else if (StringUtils.isEmpty(sysUser.getDistrict()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getDistrict())) {
            return CommonForAdminConstants.CITY;
        } else if (StringUtils.isEmpty(sysUser.getCounty()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getCounty())) {
            return CommonForAdminConstants.DISTRICT;
        } else if (StringUtils.isEmpty(sysUser.getCommunity()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getCommunity())) {
            return CommonForAdminConstants.COUNTY;
        }
        return "";
    }

    /**
     * 构造查询条件
     *
     * @param bean
     * @return
     */
    private Criteria buildQueryCond(SqfwDataMangeCheckVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        // 组装查询条件
        if (org.apache.commons.lang.StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getCreateDate);
        }
        if (StringUtils.isNotEmpty(bean.getType())) {
            criSql.andEquals(Sqfw_datamange_community::getType, bean.getType());
        } else {
            criSql.andEquals(Sqfw_datamange_community::getType, "门前三包");
        }
        // 子类型
        if (StringUtils.isNotEmpty(bean.getSubType())) {
            criSql.andEquals(Sqfw_datamange_street_check::getSubType, bean.getSubType());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 不查询已删除的内容
        criSql.andEquals(Sqfw_datamange_community::getDelFlag, false);
        // 默认查询7天内数据
        if (ObjectUtil.isEmpty(bean.getQueryTime())) {
            criSql.and(Sqfw_datamange_community::getCreateDate, ">=",
                    DateUtil.offsetDay(DateUtil.parse(CommonCheckUtils.SDF_START.format(DateUtil.yesterday())), -7));
        } else {
            criSql.andBetween(Sqfw_formSummary_new::getCreateDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryTime()));
        }
        if (StringUtils.isNotEmpty(bean.getId())) {
            criSql.andEquals("id", bean.getId());
        }
        return cri;
    }

    /**
     * 根据当前登录用户的行政区域级别获取对应审批表
     *
     * @return
     */
    private String getTableNameByArea() {
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (StringUtils.isEmpty(sysUser.getProvince()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getProvince())) {
            return DataManageConstants.DATA_MANAGE_CHECK_PROVINCE;
        } else if (StringUtils.isEmpty(sysUser.getCity()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getCity())) {
            return DataManageConstants.DATA_MANAGE_CHECK_PROVINCE;
        } else if (StringUtils.isEmpty(sysUser.getDistrict()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getDistrict())) {
            return DataManageConstants.DATA_MANAGE_CHECK_CITY;
        } else if (StringUtils.isEmpty(sysUser.getCounty()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getCounty())) {
            return DataManageConstants.DATA_MANAGE_CHECK_DISTRICT;
        } else if (StringUtils.isEmpty(sysUser.getCommunity()) || CommonForAdminConstants.ZHISHU.equals(sysUser.getCommunity())) {
            return DataManageConstants.DATA_MANAGE_CHECK_STREET;
        }
        return "";
    }
}
